<?php
// namespace protected\models\behaviors;

// require_once ('base/CBehavior.php');

/**
 * example in the model:
 * public function behaviors() {
 * return array(
 * 'CJsonBehavior'=>array(
 * 'class'=>'application.models.behaviors.CJsonBehavior'
 * ),
 * );
 * }
 */
class CJsonBehavior extends CBehavior {
	// private $owner;
	private $relations;
	public function toJson() {
		$this->owner = $this->getOwner ();
		if (is_subclass_of ( $this->owner, 'CActiveRecord' )) {
			$attributes = $this->owner->getAttributes ();
			/*$this->relations = $this->getRelated ();
			$jsonDataSource = array (
					'jsonDataSource' => array (
							'attributes' => $attributes,
							'relations' => $this->relations 
					) 
			);*/
			return Json::encode ( $attributes );
		}
		return false;
	}
	public function fromJson($json) {
		$this->owner = $this->getOwner ();
		if (is_subclass_of ( $this->owner, 'CActiveRecord' )) {
			$this->owner->setAttributes ( Json::decode ( $json ) );
			foreach ( json_decode ( $json ) as $key => $val ) {
				$this->owner->setAttribute ( $key, $val );
			}
		}
	}
	private function getRelated() {
		$related = array ();
		$obj = null;
		$md = $this->owner->getMetaData ();
		foreach ( $md->relations as $name => $relation ) {
			$obj = $this->owner->getRelated ( $name );
			$related [$name] = $obj instanceof CActiveRecord ? $obj->getAttributes () : $obj;
		}
		return $related;
	}
}

?>